<template>
  <div class="chat-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="custom-user-id">
        <span>请输入用户ID：</span>
        <input class="input-user-id" type="text" placeholder="用户ID" v-model="customUserId" />
        <button class="btn-set-user-id" @click="changeUserId">设置</button>
      </div>
      <div class="search-user">
        <span>搜索用户：</span>
        <input class="input-search" type="text" placeholder="输入用户名称" v-model="searchQuery" />
        <button class="btn-search-user" @click="filterUserList">搜索</button>
      </div>
      <div
        v-for="user in filteredUsers"
        :key="user.userId"
        class="user-item"
        @click="selectUser(user.userId)"
      >
        <span>Id={{ user.userId }}的用户:{{ user.userName }}</span>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-main">
      <!-- 聊天内容区域 -->
      <div class="chat-content" style="overflow-y: auto;">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['chat-item', !message.isUser ? 'self' : 'other']"
        >
          <!-- 用户头像和消息框 -->
          <img
            v-if="message.isUser"
            class="avatar"
            :src="'http://localhost:8007/img/get?url=己方.png'"
          />
          <div class="message-box">
            <span class="message-content">{{ message.content }}</span>
          </div>
          <!-- 用户头像在右边 -->
          <img
            v-if="!message.isUser"
            class="avatar"
            :src="'http://localhost:8007/img/get?url=对方.png'"
          />
        </div>
      </div>

      <!-- 底部输入框 -->
      <div class="chat-footer">
        <input class="input-message" type="text" placeholder="请输入消息..." v-model="message" />
        <button class="send-button" @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      messages: [], // 聊天记录
      message: "", // 当前输入的消息
      customUserId: "", // 自定义输入的用户ID
      selectedUserId: "", // 当前选中的用户ID
      searchQuery: "", // 搜索框输入内容
      users: [], // 用户列表 [{ userId: 1, userName: "User1" }, ...]
      filteredUsers: [], // 搜索结果过滤后的用户列表
      ws: null // WebSocket 连接实例
    };
  },
  methods: {
    // 切换用户ID
    changeUserId() {
      if (!this.customUserId.trim()) {
        alert("请输入用户ID");
        return;
      }
      this.selectedUserId = `user${this.customUserId}`;
      this.loadMessages(); // 根据新用户ID加载消息
    },

    // 搜索用户
    filterUserList() {
      this.filteredUsers = this.users.filter(user =>
        user.userName.includes(this.searchQuery.trim())
      );
    },

    // 选择用户
    selectUser(userId) {
      this.selectedUserId = "user" + userId;
      this.customUserId = userId; // 更新自定义输入框
      this.loadMessages();
    },

    // 加载缓存中的消息记录
    loadMessages() {
      const cachedMessages =
        JSON.parse(localStorage.getItem("chatMessages")) || [];
      this.messages = cachedMessages.filter(
        msg =>
          (msg.from === this.selectedUserId && msg.to === "admin1") ||
          (msg.from === "admin1" && msg.to === this.selectedUserId)
      );
    },

    fetchUserNames() {
      const cachedMessages =
        JSON.parse(localStorage.getItem("chatMessages")) || [];

      // 如果缓存消息为空，直接返回
      if (cachedMessages.length === 0) {
        console.log("缓存消息为空，跳过用户名称请求");
        return;
      }

      const userIds = [
        ...new Set(
          cachedMessages
            .filter(msg => msg.from && msg.from.startsWith("user"))
            .map(msg => parseInt(msg.from.replace("user", ""), 10))
        )
      ];

      // 如果提取的 userIds 数组为空，也跳过请求
      if (userIds.length === 0) {
        console.log("没有有效的用户ID，跳过用户名称请求");
        return;
      }
      console.log(userIds);

      // 请求用户名称
      this.$axios
        .post("http://localhost:8006/user/getUsersName", userIds)
        .then(res => {
          if (res.data && res.data.data) {
            this.users = res.data.data; // [{userId: int, userName: string}, ...]
            this.filteredUsers = this.users; // 初始化用户列表
            console.log("用户姓名查询成功：", res.data.data);
          }
        })
        .catch(err => {
          console.error("用户姓名查询失败:", err);
        });
    },

    connectWebSocket() {
      if (this.ws) {
        this.ws.close(); // 如果已有连接，关闭它
      }

      const wsUrl = "ws://localhost:8006/ws?userId=admin1"; // 用户ID为admin1
      this.ws = new WebSocket(wsUrl);

      this.ws.onopen = () => {
        console.log("WebSocket 连接成功");
        alert("WebSocket 连接成功");
      };

      this.ws.onmessage = event => {
        const receivedData = JSON.parse(event.data); // 解析接收到的消息
        console.log("接收到消息:", receivedData);
        let newMessage = {
          from: receivedData.from, // 替换为当前用户ID
          to: "admin1",
          content: receivedData.message,
          isUser: true,
          time: receivedData.time
        };
        // 添加到消息记录
        if (newMessage.from === this.selectedUserId) {
          this.addMessage(newMessage);
        }
        this.updateCache(newMessage);
      };

      this.ws.onclose = () => {
        console.log("WebSocket 连接已关闭");
        alert("WebSocket 已关闭");
      };

      this.ws.onerror = err => {
        console.error("WebSocket 出现错误:", err);
        alert("WebSocket 错误");
      };
    },

    // 发送消息
    sendMessage() {
      if (!this.message.trim()) {
        alert("请输入内容");
        return;
      }

      const newMessage = {
        from: "admin1", // 替换为当前用户ID
        to: this.selectedUserId,
        content: this.message,
        isUser: false,
        time: new Date().toISOString()
      };

      // 添加到本地消息记录
      this.addMessage(newMessage);
      this.updateCache(newMessage);

      // 模拟发送消息到后端
      this.$axios
        .get(`http://localhost:8006/chat/send`, {
          params: {
            from: "admin1", // 替换为当前用户ID
            to: this.selectedUserId,
            content: this.message
          }
        })
        .then(res => {
          console.log("消息发送成功:", res.data);
          alert("消息发送成功");
        })
        .catch(err => {
          console.error("消息发送失败:", err);
          alert("消息发送失败");
        });

      this.message = ""; // 清空输入框
    },

    // 添加消息记录并存储到缓存
    addMessage(newMessage) {
      const lastMessage = this.messages[this.messages.length - 1];

      // 检查是否需要插入时间分割
      if (
        lastMessage &&
        new Date(newMessage.time) - new Date(lastMessage.time) > 5 * 60 * 1000
      ) {
        this.messages.push({
          content: newMessage.time,
          isTimeDivider: true
        });
      }

      this.messages.push(newMessage);
    },

    updateCache(newMessage) {
      // 获取当前缓存中的消息
      const cachedMessages =
        JSON.parse(localStorage.getItem("chatMessages")) || [];

      // 将新消息添加到缓存
      cachedMessages.push(newMessage);

      // 更新缓存
      localStorage.setItem("chatMessages", JSON.stringify(cachedMessages));
    }
  },
  mounted() {
    this.connectWebSocket();
    this.fetchUserNames(); // 获取用户列表
    this.loadMessages(); // 加载历史消息
  }
};
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: row;
  height: 100vh;
  background-color: #f4f4f4;
}

.sidebar {
  width: 25%;
  background-color: #f9f9f9;
  border-right: 1px solid #ddd;
  padding: 10px;
  box-sizing: border-box;
  overflow-y: auto;
}

.custom-user-id,
.search-user {
  margin-bottom: 15px;
}

.input-user-id,
.input-search {
  width: calc(100% - 60px);
  padding: 5px;
  margin-right: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  box-sizing: border-box;
}

.btn-set-user-id,
.btn-search-user {
  padding: 5px 10px;
  border: none;
  background-color: #007aff;
  color: #fff;
  border-radius: 5px;
  cursor: pointer;
}

.user-item {
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.user-item:hover {
  background-color: #f0f0f0;
}

.chat-main {
  width: 75%;
  display: flex;
  flex-direction: column;
}

.chat-content {
  flex: 1;
  padding: 10px;
  background-color: #f4f4f4;
  overflow-y: auto;
}

.chat-footer {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  border-top: 1px solid #ddd;
}

.input-message {
  flex: 1;
  height: 40px;
  padding: 0 10px;
  border: 1px solid #ddd;
  border-radius: 20px;
}

.send-button {
  margin-left: 10px;
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
  background-color: #007aff;
  color: #fff;
  border-radius: 20px;
  border: none;
}

.chat-header {
  height: 50px;
  line-height: 50px;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  background-color: #fff;
  border-bottom: 1px solid #ddd;
}

.chat-content {
  flex: 1;
  padding: 10px;
  background-color: #f4f4f4;
  overflow-y: auto;
}

.chat-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 5%;
  /* 消息之间的间隔 */
  width: 100%;
  /* 保证整体宽度为100% */
}

.chat-item.self {
  justify-content: flex-end;
  /* 用户消息靠右 */
}

.chat-item.other {
  justify-content: flex-start;
  /* 对方消息靠左 */
}

.avatar {
  width: 6vw;
  /* 头像宽度为屏幕的15% */
  height: 6vw;
  border-radius: 50%;
  /* 圆形头像 */
  margin: 0 5%;
  /* 距离屏幕边缘5% */
}

.message-box {
  max-width: 60%;
  /* 消息宽度为屏幕的60% */
  padding: 10px;
  /* 内边距 */
  border-radius: 10px;
  /* 圆角 */
  background-color: #fff;
  /* 背景色 */
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  /* 阴影 */
  box-sizing: border-box;
  /* 让 padding 不影响 width */
  word-wrap: break-word;
  /* 长单词换行 */
  overflow-wrap: break-word;
  /* 兼容性换行 */
}

.chat-item.self .message-box {
  background-color: #007aff;
  color: #fff;
}

.chat-item.self .message-box:after {
  right: -5px;
  /* 调整三角形位置 */
  border-left-color: #007aff;
  /* 三角形颜色 */
}

.chat-item.other .message-box:after {
  left: -5px;
  /* 调整三角形位置 */
  border-right-color: #fff;
  /* 三角形颜色 */
}

.message-box:after {
  content: "";
  position: absolute;
  top: 10px;
  width: 0;
  height: 0;
  border: 5px solid transparent;
}

.message-content {
  font-size: 14px;
  line-height: 20px;
}

.chat-footer {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  border-top: 1px solid #ddd;
}

.input-message {
  flex: 1;
  height: 40px;
  padding: 0 10px;
  border: 1px solid #ddd;
  border-radius: 20px;
}

.send-button {
  margin-left: 10px;
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
  background-color: #007aff;
  color: #fff;
  border-radius: 20px;
  border: none;
}
</style>
